# coding: utf-8
# author:lishikai markdown.md ==> html ==> xmind
import markdown
import xmind
import json


class element_sort(object):
    def __init__(self, id, title, link):
        self.id = id
        self.title = title
        self.link = link

    def __lt__(self, other):  # override <操作符
        return self.id < other.id

    def __str__(self):  # override __str__
        return "id={0},title={1}".format(self.id, self.name)


def markdown_xmind_generator(file):

    html = markdown.markdown(file)
    lines = html.split("\n")
    title = lines[1][9:]
    #
    i = 0
    tmph = 0
    tmpp = ""
    newh = 1
    #
    workbook = xmind.load(title + '.xmind')
    sheet = workbook.getPrimarySheet()
    # ***** 第一个画布 *****
    sheet.setTitle(title)
    root_topic = sheet.getRootTopic()
    root_topic.setTitle(title)
    end_topic = root_topic
    first_load = True
    for line in lines:
        print(line)
        ifH = line.startswith("<h") and line.startswith("<hr") == False
        ifP = line.startswith("<p") and line.endswith("p>")
        #

        if (ifH):
            nodetype = 0
            title = line[4:-5]
            if (tmpp != ""):
                end_topic.setPlainNotes(tmpp) # 为了保留文本内容给上一节点
            tmpp = ""
            newh = int(line[2])

            if (first_load):
                nodetype = 2
            else:
                if (newh > tmph): nodetype = 0  # 产生新的节点
                if (newh == tmph): nodetype = 1  # 产生兄弟节点
                if (newh < tmph): nodetype = 2  # 产生父亲下子节点

            if nodetype == 0:
                begin_topic = end_topic;
                end_topic = end_topic.addSubTopic()
                end_topic.setTitle(title)

            if nodetype == 1:
                end_topic = begin_topic.addSubTopic()
                end_topic.setTitle(title)

            if nodetype == 2:  # 2->1  h2 - >h3 - >h4 ->
                end_topic = root_topic.addSubTopic()
                end_topic.setTitle(title)
                begin_topic = root_topic
                if (first_load):
                    first_load = False

        elif (ifP):
            p = line[3:-4]
            tmpp = tmpp + "\n" + p;
            # 长度超出直接赋值，不再判断是否是h
            if ((i + 1) == lines.__len__()):
                if (nodetype == 1):
                    end_topic.setPlainNotes(tmpp)
                else:
                    end_topic.setPlainNotes(tmpp)
            else:
                ifnexth = lines[i + 1].startswith("<h")
                if (ifnexth):
                    if (nodetype == 1):
                        end_topic.setPlainNotes(tmpp)
                    else:
                        end_topic.setPlainNotes(tmpp)
        else:
            tmpp = tmpp + "\n" + line;
        tmph = newh
        i = i + 1;
    xmind.save(workbook)

#     xmind=>scrapy 通过xmind爬链接的算法（实现去重功能）
def xmind_generator_title_url(xmind_filename):

    workbook = xmind.load(xmind_filename)
    json1 = workbook.to_prettify_json()
    json1 = json.loads(json1.replace('\n', '').replace('\r', ''))
    # firstload = True
    jsondata = {}
    totaldata_array = []
    directory = json1[0]['topic']['label']
    label = json1[0]['topic']['comment']
    jsondata['directory'] = directory
    jsondata['label'] = label
    newnodes = json1[0]['topic']['topics']
    while(newnodes!=[]):
        nodes = newnodes
        newnodes = []
        for node in nodes:
            if('link' in node.keys()):
                if(node['link']!=None):
                    # totaldata_array.append((node["title"], node["link"], node["id"]))
                    totaldata_array.append(element_sort(title=node["title"], link=node["link"], id=node["id"]))
                else:
                    totaldata_array.append(element_sort(title=node["title"], link="", id=node["id"]))
            else:
                totaldata_array.append(element_sort(title=node["title"], link="", id=node["id"]))
            if('topics' in node.keys()):
                newnodes.extend(node["topics"])


    # totaldata_array = sorted(totaldata_array, key=lambda s: s[2], reverse=False)  暂时不实现哪种，本方式只是一句优秀内容进行爬虫学习
    # totaldata_array.sort()
    for each in totaldata_array:
        print(each.title)
        print(each.link)
        print(each.id)
    jsondata.setdefault('totaldata_array', []).extend(totaldata_array)
    return jsondata;

    pass


if __name__ == '__main__':
    file = open(r'C:\Users\22934\PycharmProjects\wp_scrapy_util\wp_scrapy_util\wp_scrapy_util\spiders\虚拟化平台建设.md', 'r',
                encoding='utf-8').read()
    markdown_xmind_generator(file)
#     #
#     # xmind_generator_title_url()

